package com.sky.service.impl;

import com.sky.annotation.AutoFill;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.enumeration.OperationType;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.apache.poi.sl.usermodel.Background;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {
    @Autowired
    private AddressBookMapper addressBookMapper;

    /*
    * 新增地址
    * */
    public void save(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(StatusConstant.DISABLE);
        addressBookMapper.insert(addressBook);
    }

    /*
    * 查询当前登录用户的所有地址信息
    * */
    public List<AddressBook> selectListByUserId() {
        List<AddressBook> list = addressBookMapper.selectListByUserId(BaseContext.getCurrentId());
        return list;
    }
    /*
    * 查询默认地址
    * */
    @Override
    public AddressBook getDefaultAddressBook() {
        Long userId = BaseContext.getCurrentId();
        AddressBook addressBook = addressBookMapper.getDefaultAddressBook(userId);
        if (addressBook == null){
            List<AddressBook> addressBooks = addressBookMapper.selectListByUserId(userId);
            if (addressBooks != null && addressBooks.size() >0){
                addressBook = addressBooks.get(0);
            }
        }
        return addressBook;
    }
    /*
    * 根据id查询地址
    * */
    public AddressBook getAddressByID(Long id) {
        return addressBookMapper.getAddressByID(id);
    }
    /*
    * 根据id修改地址
    * */
    public void updateAddress(AddressBook addressBook) {
        addressBookMapper.updateAddressById(addressBook);
    }

    /*
    * 设置默认地址
    * */
    @Transactional(rollbackFor = Exception.class)
    public void updateAddressIsDefault(AddressBook addressBook) {
        AddressBook defaultAddressBook = addressBookMapper.getDefaultAddressBook(BaseContext.getCurrentId());
        if (defaultAddressBook != null){
            defaultAddressBook.setIsDefault(StatusConstant.DISABLE);
            addressBookMapper.updateAddressById(defaultAddressBook);
        }
        addressBook.setIsDefault(StatusConstant.ENABLE);
        addressBookMapper.updateAddressById(addressBook);
    }

    /*
    * 根据id删除地址
    * */
    public void deleteAddressBookById(Long id) {
        addressBookMapper.deleteAddressBookById(id);
    }
}
